package ray.mgocc;

import java.text.ParseException;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.util.regex.MatchResult;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class Time implements Comparable{

    private final static Log log = LogFactory.getLog(Time.class);

    private static final char SEPARATOR = ':';
    //    private static Pattern FORMAT = Pattern.compile("([0-9]{2,}):([0-9]{2}):([0-9]{2})");
    private static Pattern FORMAT = Pattern.compile("([0-9]*):([0-9]*):([0-9]*)");
    private static final int MAX_SECONDS = 60;
    private static final int MAX_MINUTES = 60;
    public  static final int A_HOUR = MAX_MINUTES * MAX_SECONDS;
    private long second;
    public Time(){
        this(0);
    }
    public Time(long second){
        this.second = second;
    }
    public Time(String time) throws ParseException{
        this(parse(time));
    }
    public static long parse(String time) throws ParseException{
        long second = 0;
        Matcher result = FORMAT.matcher(time);
        if(!result.matches()){
            throw new ParseException(time,0);
        }
        int seq = 0;
        try{
            if(3 != result.groupCount()){
                throw new ParseException(time,0);
            }
            second += Integer.parseInt(result.group(1)) * A_HOUR;
            
            seq = 2;
            int minute = Integer.parseInt(result.group(seq));
            if(MAX_MINUTES <= minute){
                throw new ParseException("Minutes over "+MAX_MINUTES,result.start(seq));
            }
            second += minute * MAX_SECONDS;
            
            seq = 3;
            int sec = Integer.parseInt(result.group(seq));
            if(MAX_SECONDS <= sec){
                throw new ParseException("Seconds over "+MAX_SECONDS,result.start(seq));
            }
            second += sec;
        }catch(NumberFormatException e){
            throw new ParseException(time+" parse error.",0);
        }

        return second;
    }
    public static boolean match(String time){
        return FORMAT.matcher(time).matches();
    }
    public String toString(){
        return String.format("%02d"+SEPARATOR+"%02d"+SEPARATOR+"%02d",
                             new Integer(getHour()),
                             new Integer(getMinute()),
                             new Integer(getSecond()));
    }
    public int getHour(){
        return (int)(second / A_HOUR);
    }
    public int getMinute(){
        return (int)(second % A_HOUR / MAX_MINUTES) ;
    }
    public int getSecond(){
        return (int)(second % MAX_MINUTES);
    }
    public long toSecond(){
        return this.second;
    }
    public int compareTo(Object that){
        return (int)(this.toSecond() - ((Time)that).toSecond());
    }
    public boolean equals(Object that){
        return 0 == compareTo(that);
    }
}
